var util = require('util_ky.js');
import {
  wxRequest
} from './server.js';
const _wxRequest = new wxRequest();
const app = getApp();
var status = "";
var sousuo = "";
var connectedDeviceId = ""; //已连接设备uuid
var services = ""; // 连接设备的服务
var characteristics = ""; // 连接设备的状态值
var writeServicweId = ""; // 可写服务uuid
var writeCharacteristicsId = ""; //可写特征值uuid
var readServicweId = ""; // 可读服务uuid
var readCharacteristicsId = ""; //可读特征值uuid
var notifyServicweId = ""; //通知服务UUid
var notifyCharacteristicsId = ""; //通知特征值UUID
var inputValue = "";
var characteristics1 = ""; // 连接设备的状态值

// 重连最大次数
let retryCount = 5;

var mac = ""; //mac
var down_hex = ""; //服务器将要发给设备的十六进制的数据
var msg = '';
var bt_temp_data = ""; //蓝牙缓存数据
var ok_write = false;
var bt_setInterval = null;

var conn_callback;//
var write_callback;//
var notify_callback;
var read_callback;

////////////////页面加载开始
var openBlue = function (_mac, btid, c_callback, w_callback, r_callback, n_callback) {
  conn_callback = c_callback;
  write_callback = w_callback;
  read_callback = r_callback;
  notify_callback = n_callback
  typeof conn_callback == "function" && conn_callback("蓝牙连接中");
  mac = _mac;
  //搜索蓝牙
  if (btid) {
    var isbt = check_bt(app);
    //console.log("isbt=" + isbt);
    if (isbt) {
      init(function() {
        lanya3(function(res) {
          console.log("搜索蓝牙==========");
          console.log(res);
          typeof conn_callback == "function" && conn_callback("蓝牙搜索中");
          if (app.getPlatform() == 'ios') {
            //如果是苹果
            lanya4(function(res) {
              console.log("lanya4", res);
              if (res) {
                var length = res.length;
                for (var i = 0; i < length; i++) {
                  var name = res[i].name;
                  //XY123456789010
                  console.log("name=" + name + " btid=" + btid);
                  if (name == mac) {
                    btid = res[i].deviceId;
                    break;
                  }
                }
              }
              console.log("btid=" + btid);
              starBlue(btid);
              //starBlue('98B2686E-35D8-3C47-18B4-7A3A9867C8CC')
            });
          } else {
            //btid = util.get_bt_address(btid);
            starBlue(btid);
          }
        }, function(res) {});

      }, function(res) {
        wx.showModal({
          content: "初始化错误："+res,
          showCancel: false
        });
      });
    }
  }
}
// 蓝牙装置开启事件
var starBlue = function(btid) {
  console.log("starBlue-mac=" + mac + " starBlue-btid蓝牙" + btid);
  connectTO(btid, function() {
    //console.log("蓝牙连接成功deviceid=" + deviceid);
    typeof conn_callback == "function" && conn_callback("蓝牙连接成功 蓝牙tid=" + btid);
    
    lanya7(function() {
      //console.log("获取连接设备的所有特征值成功：deviceid=" + deviceid);
      lanya9(function() {
        //console.log("接收广播成功：deviceid=" + deviceid);
        //interval_bt();
        //console.log('发送', down_hex);
        //write_value(down_hex);
        typeof notify_callback == "function" && notify_callback()
        lanya10(function(hex) {
          // console.log("读取=" + hex);
          // console.log(hex);
        }, function(res) {
          console.log("读取蓝牙数据失败：" + res);
        }, function(hex) {
          console.log(888, hex);
          // sendText = that.sendrules(hex)
          //console.log("读取蓝牙数据=" + hex);
          //var bt_info = get_bt_data(hex);
          var bt_info = hex;
          //console.log("bt_info=" + bt_info);
          if(!hex.startsWith("66")) {
            console.log('不是66开头的合法数据')
            return ;
          }
          if (bt_info) {
            console.log("读取：" + bt_info);
            typeof read_callback == "function" && read_callback('接收：' + bt_info);
            var up_info = bt_info.replace("AA", "55");
            //console.log("上传到服务器 mac=" + mac + " up_info=" + up_info);
            set_hex_devicecommand(mac, up_info);
            ok_write = true;
          }
        });
      }, function(res) {
        console.log("接收广播失败：" + res);
        typeof conn_callback == "function" && conn_callback("接收广播失败：" + res);
      });
    }, function(res) {
      console.log("获取连接设备的所有特征值失败：" + res);
      typeof conn_callback == "function" && conn_callback("获取连接设备的所有特征值失败：" + res);
    })
  }, function(res) {
    console.log('蓝牙链接失败：' + res);
    typeof conn_callback == "function" && conn_callback('蓝牙链接失败：' + res);
  })
}


//初始化
var init = function(success, fail) {
  wx.openBluetoothAdapter({
    success: function(res) {
      typeof success == "function" && success(res);
      //监听蓝牙适配器状态
      wx.onBluetoothAdapterStateChange(function(res) {
        console.log('是否可用蓝牙', res);
        sousuo = res.discovering ? "在搜索" : "未搜索";
        status = res.available ? "可用" : "不可用";
      });
    },
    fail: function(res) {
      //console.log("初始化失败 " + res.errMsg);
      typeof fail == "function" && fail(res.errMsg);
    },
    complete: function() {
      console.log("初始化结束");
    }
  });
}

//搜索设备
var lanya3 = function(success, fail) {
  wx.startBluetoothDevicesDiscovery({
    powerLevel: "high",
    success: function(res) {

      console.log("搜索设备：" + JSON.stringify(res));
      typeof success == "function" && success(res);
      //监听蓝牙适配器状态
      wx.onBluetoothAdapterStateChange(function(res) {
        sousuo = res.discovering ? "在搜索" : "未搜索";
        status = res.available ? "可用" : "不可用";
      })
    },
    fail: function(res) {
      console.log("搜索失败" + res.errMsg);
      typeof fail == "function" && fail(res.errMsg);
      typeof conn_callback == "function" && conn_callback("搜索失败" + res.errMsg);
    },
    complete: function() {
      console.log("搜索结束");
    }
  })
}

// 获取所有已发现的设备
var lanya4 = function(success, fail) {
  wx.getBluetoothDevices({
    success: function(res) {
      console.log("获取设备", res);
      //是否有已连接设备
      // wx.getConnectedBluetoothDevices({
      //   success: function(res) {
      //     typeof success == "function" && success(res);
      //     console.log('zjj-device', res);
      //     if (res.deviceId) {
      //       connectedDeviceId = res.deviceId;
      //     }
      //   }
      // });
      typeof success == "function" && success(res.devices);
      //devices = res.devices;
      //监听蓝牙适配器状态
      wx.onBluetoothAdapterStateChange(function(res) {
        sousuo = res.discovering ? "在搜索" : "未搜索";
        status = res.available ? "可用" : "不可用";
      });
    },
    fail: function(res) {
      console.log("获取列表错误：" + res.errMsg);
      typeof conn_callback == "function" && conn_callback("获取列表错误：" + res.errMsg);
    }
  })
}

//获取连接设备的所有特征值  for循环获取不到值
var lanya7 = function(success, fail) {
  console.log("abab", services);

  wx.getBLEDeviceCharacteristics({
    // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
    deviceId: connectedDeviceId,
    // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
    serviceId: services[0].uuid,
    success: function(res) {
      console.log(services[0].uuid, res.characteristics)
      for (var i = 0; i < res.characteristics.length; i++) {
        if (res.characteristics[i].properties.notify) {
          notifyServicweId = services[0].uuid;
          notifyCharacteristicsId = res.characteristics[i].uuid;
        }
        if (res.characteristics[i].properties.write) {
          writeServicweId = services[0].uuid;
          writeCharacteristicsId = res.characteristics[i].uuid;
        } else if (res.characteristics[i].properties.read) {
          readServicweId = services[0].uuid;
          readCharacteristicsId = res.characteristics[i].uuid;
        }

        if (notifyServicweId && notifyCharacteristicsId) {
          typeof success == "function" && success();
        }
      }
      //typeof success == "function" && success();
    },
    fail: function(res) {
      typeof fail == "function" && fail(res.errMsg);
      //console.log("fail");
    },
    complete: function() {}
  })
  wx.getBLEDeviceCharacteristics({
    // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
    deviceId: connectedDeviceId,
    // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
    serviceId: services[1].uuid,
    success: function(res) {
      console.log(services[1].uuid, res.characteristics)
      for (var i = 0; i < res.characteristics.length; i++) {
        if (res.characteristics[i].properties.notify) {
          notifyServicweId = services[1].uuid;
          notifyCharacteristicsId = res.characteristics[i].uuid;
        }
        if (res.characteristics[i].properties.write) {
          writeServicweId = services[1].uuid,
            writeCharacteristicsId = res.characteristics[i].uuid

        } else if (res.characteristics[i].properties.read) {
          readServicweId = services[1].uuid
          readCharacteristicsId = res.characteristics[i].uuid
        }
      }
      //console.log('serviceId777=' + notifyServicweId)
      //console.log('characteristicId777=' + notifyCharacteristicsId)
      typeof success == "function" && success();
    },
    fail: function(res) {
      console.log("wx.getBLEDeviceCharacteristics错误：" + res.errMsg);
    },
    complete: function() {}
  })
  //console.log('777' + notifyServicweId)
  //console.log('777' + notifyCharacteristicsId)
  // if (notifyServicweId && notifyCharacteristicsId){
  //   typeof success == "function" && success();
  // }
}
//连接设备
var connectTO = function(deviceid, success, fail) {
  wx.createBLEConnection({
    timeout: 3000,
    deviceId: deviceid,
    success: function(res) {
      console.log('success', res);
      connectedDeviceId = deviceid;
      msg = "已连接" + deviceid;
      console.log(msg)
      //// 获取连接设备的service服务
      wx.getBLEDeviceServices({
        // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
        deviceId: connectedDeviceId,
        success: function(res) {
          services = res.services;
          msg = JSON.stringify(res.services);
          typeof success == "function" && success();
        },
        fail: (res) => {
          console.log(res);
        }
      });
    },
    fail: function(res) {
      console.log('fail', res);
      if(retryCount > 0) {
        console.log('尝试重连', res, '剩余次数', retryCount);
        retryCount--;
        connectTO(deviceid, success, fail)
      }else{
        
        retryCount = 5;
        // 重置蓝牙
        //wx.stopBluetoothDevicesDiscovery();
        //wx.offBluetoothDeviceFound();
        //wx.offBluetoothAdapterStateChange();
        //wx.closeBluetoothAdapter();
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '蓝牙信号弱，请尽量靠近设备或重启设备后重试',
          confirmText: '我知道了',
          showCancel: false
        })
      }
      // typeof fail == "function" && fail(res.errMsg);
      // console.log("连接失败" + res.errMsg);
      // typeof conn_callback == "function" && conn_callback("连接失败" + res.errMsg);
    },
    complete: function(res) {
      console.log('complete', res);
      //console.log("连接结束");
    }
  })
  // wx.closeBLEConnection({
  //   deviceId: deviceid,
  //   success: function(res) {
  //     console.log("连接关闭设备", res);
  //     wx.createBLEConnection({
  //       deviceId: deviceid,
  //       success: function(res) {
  //         //console.log(res.errMsg);
  //         connectedDeviceId = deviceid;
  //         msg = "已连接" + deviceid;
  //         //// 获取连接设备的service服务
  //         wx.getBLEDeviceServices({
  //           // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
  //           deviceId: connectedDeviceId,
  //           success: function(res) {
  //             services = res.services;
  //             msg = JSON.stringify(res.services);
  //             typeof success == "function" && success();
  //           }
  //         });
  //       },
  //       fail: function(res) {
  //         console.log('尝试重连', res);
  //         connectTO(deviceid, success, fail)
  //         // typeof fail == "function" && fail(res.errMsg);
  //         // console.log("连接失败" + res.errMsg);
  //         // typeof conn_callback == "function" && conn_callback("连接失败" + res.errMsg);
  //       },
  //       complete: function() {
  //         //console.log("连接结束");
  //       }
  //     })
  //   },
  //   fail: function(res) {
  //     console.log("关闭蓝牙失败", res);
  //     console.log("deviceid123", deviceid);
  //     wx.createBLEConnection({
  //       timeout: 3000,
  //       deviceId: deviceid,
  //       success: function(res) {
  //         //console.log(res.errMsg);
  //         connectedDeviceId = deviceid;
  //         msg = "已连接" + deviceid;
  //         //// 获取连接设备的service服务
  //         wx.getBLEDeviceServices({
  //           // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
  //           deviceId: connectedDeviceId,
  //           success: function(res) {
  //             services = res.services;
  //             msg = JSON.stringify(res.services);
  //             typeof success == "function" && success();
  //           }
  //         });
  //       },
  //       fail: function(res) {
  //         console.info('错这里');
  //         console.info(res);
  //         typeof fail == "function" && fail(res.errMsg);
  //         typeof conn_callback == "function" && conn_callback(res.errMsg);
  //       },
  //       complete: function() {
  //         //console.log("连接结束");
  //       }
  //     })
  //   }
  // })
}



var write_value = function(str) {
  //console.log('write_value发送str=' + str);
  //0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
  var bytes = 2048;
  //var byte_length = byte.length;
  //var send_str = byte.substring(0,40);

  var byte_length = str.length;
  if (byte_length == 0)
    return;
  var index = parseInt(byte_length / bytes); // 分几次发送
  //console.log('发送index=' + index);
  //console.log('发送byte_length % bytes=' + (byte_length % bytes));
  if (byte_length % bytes != 0) {
    index = index + 1;
  }
  //console.log('发送index2222=' + index);
  for (var k = 0; k < index; k++) {
    var send_str = str.substring(k * bytes, k * bytes + bytes);

    var buf = util.hexString2ArrayBuffer(send_str.toUpperCase());
    var now = new Date();
    //console.log('写入=' + now + " " + util.arrayBuffer2HexString(buf));
    
    lanya8(buf, function(res) {}, function(res) {});
    util.sleep(10);
  }
}
//发送
var lanya8 = function(buf, success, fail) {
  //console.log('开始发送1')
  // 这里的回调可以获取到 write 导致的特征值改变
  // wx.onBLECharacteristicValueChange(function (characteristic) {
  //   console.log('characteristic value changed:1', characteristic)
  // })
  // var buf = new ArrayBuffer(1);
  // let dataView = new DataView(buf);
  //写入通道指令 
  //dataView.setUint8(0, 0xA5); //这里也能写十进制数

  wx.writeBLECharacteristicValue({
    // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
    deviceId: connectedDeviceId,
    // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
    //serviceId: writeServicweId,
    serviceId: writeServicweId,
    // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
    //characteristicId: writeCharacteristicsId,
    characteristicId: writeCharacteristicsId,
    // 这里的value是ArrayBuffer类型
    value: buf,
    success: function(res) {
      typeof success == "function" && success(res);
      //console.log('写入成功=' + JSON.stringify(res));
      typeof write_callback == "function" && write_callback(util.arrayBuffer2HexString(buf));
    },
    fail: function(res) {
      typeof fail == "function" && fail(res.errMsg);
      console.log("写入失败：" + res.errMsg, util.arrayBuffer2HexString(buf));
      typeof write_callback == "function" && write_callback(res.errMsg);
    },
    complete: function() {
      //console.log("写入结束");
    }
  });
  /**
   * 坑就在这里了，对于安卓系统，需要添加下面这段代码。你写完数据后，还必须读一次，才能被onBLECharacteristicValueChange监听到，才会把数据返回给你，
   * 但在苹果系统里面就不能有下面这段代码了，因为如果你添加上去的话，会出现发一次指令出现两次返回值的情况
   */
  wx.readBLECharacteristicValue({
    deviceId: connectedDeviceId,
    serviceId: notifyServicweId,
    characteristicId: notifyCharacteristicsId,
    success: function(res) {
      //console.log('readBLECharacteristicValue' + res);
    }
  });
}

//启用低功耗蓝牙设备特征值变化时的 notify 功能(开通接收广播)
var lanya9 = function(success, fail) {
  //console.log('deviceId=' + connectedDeviceId)
  //console.log('serviceId999=' + notifyServicweId)
  //console.log('characteristicId999=' + notifyCharacteristicsId)
  wx.notifyBLECharacteristicValueChange({
    state: true, // 启用 notify 功能
    // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
    deviceId: connectedDeviceId,
    // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
    serviceId: notifyServicweId,
    // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
    characteristicId: notifyCharacteristicsId,
    success: function(res) {
      console.log('成功开通接收广播', res);
      typeof success == "function" && success(res);
      typeof conn_callback == "function" && conn_callback('成功开通接收广播');
    },
    fail: function(res) {
      //console.log('notify错误：' + res.errMsg);
      typeof fail == "function" && fail(res.errMsg);
      typeof conn_callback == "function" && conn_callback('接收广播失败：' + res.errMsg);
    },
  });
}

//接收消息
var lanya10 = function(success, fail, resdata) {
  // 必须在这里的回调才能获取
  wx.onBLECharacteristicValueChange(function(characteristic) {
    let hex = Array.prototype.map.call(new Uint8Array(characteristic.value), x => ('00' + x.toString(16)).slice(-2)).join('');
    // console.log("接收到的十六进制数据：" + JSON.stringify(characteristic) + ":" + hex);
    typeof resdata == "function" && resdata(hex);
  })
  //console.log(that.data.readServicweId);
  //console.log(that.data.readCharacteristicsId);

  wx.readBLECharacteristicValue({
    // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
    deviceId: connectedDeviceId,
    // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
    serviceId: notifyServicweId,
    // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
    characteristicId: notifyCharacteristicsId,
    success: function(res) {
      console.log('success读取Notify123123=======');
      console.log(res);
      typeof success == "function" && success(res);
     
    },
    fail: function(res) {
      console.log("读取错误=" + res.errMsg);
      typeof read_callback == "function" && read_callback('接收设备数据错误 ' + res.errMsg);
      typeof fail == "function" && fail(res.errMsg);
    },
    complete: function() {
      //console.log("接收结束");
    }
  })

  wx.readBLECharacteristicValue({
    // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
    deviceId: connectedDeviceId,
    // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
    serviceId: readServicweId,
    // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
    characteristicId: readCharacteristicsId,
    success: function(res) {
      console.log('success读取=======');
      console.log(res);
      typeof success == "function" && success(res);
     
    },
    fail: function(res) {
      console.log("读取错误=" + res.errMsg);
      typeof read_callback == "function" && read_callback('接收设备数据错误 ' + res.errMsg);
      typeof fail == "function" && fail(res.errMsg);
    },
    complete: function() {
      //console.log("接收结束");
    }
  })
}
/////////////////////////蓝牙设备验证/
var check_bt = function(app) {
  //蓝牙设备基础手机版本提示
  if ((app.getPlatform() == 'android' && versionCompare('6.5.7', app.getVersion()))) {
    var str ="当前微信版本过低，请更新至最新版本";
    wx.showModal({
      title: '提示',
      content: str,
      showCancel: false
    });
    typeof conn_callback == "function" && conn_callback(str);
    return false
  } else if (app.getPlatform() == 'ios' && versionCompare('6.5.6', app.getVersion())) {
    var str = "当前微信版本过低，请更新至最新版本";
    wx.showModal({
      title: '提示',
      content: str,
      showCancel: false
    });
    typeof conn_callback == "function" && conn_callback(str);
    return false
  }
  return true;
}

var close_bt = function(btid, success, fail) {
  wx.closeBLEConnection({
    deviceId: btid,
    success: function(res) {
      typeof success == "function" && success(res);
      typeof conn_callback == "function" && conn_callback('成功关闭蓝牙');
    },
    fail: function(res) {
      typeof fail == "function" && fail(res.errMsg);
      typeof conn_callback == "function" && conn_callback('关闭蓝牙错误 ' + res.errMsg);
    },
    complete: function() {}
  });
}

///////////////////////////////////////////
//版本比较逻辑
var versionCompare = function(ver1, ver2) {
  var version1pre = parseFloat(ver1)
  var version2pre = parseFloat(ver2)
  var version1next = parseInt(ver1.replace(version1pre + ".", ""))
  var version2next = parseInt(ver2.replace(version2pre + ".", ""))
  if (version1pre > version2pre)
    return true
  else if (version1pre < version2pre)
    return false
  else {
    if (version1next > version2next)
      return true
    else
      return false
  }
}

//拼接设备用蓝牙传回的数据，多段拼成合法的数据
var get_bt_data = function(data) {
  data = data.toUpperCase();
  if (data.startsWith("55"))
    return "";

  if (!bt_temp_data.startsWith("AA")) {
    bt_temp_data = "";
  }
  // 数据格式
  // 55 00 0A 00 00 00 00 00 00 20 00 00 17 12 10 21 09 40 00 00 00 00 00
  // 00 00 88 A1 40 1F 9F 7E 7E 01 02 03 04 05 00 00 00 00 00 C1 55

  if (data.indexOf("AA") == 0) {
    bt_temp_data = data.trim();
  } else {
    bt_temp_data = bt_temp_data + data.trim();
  }
  if (bt_temp_data.length >= 88) {
    var str = bt_temp_data.substring(0, 88);
    bt_temp_data = "";
    return str;
  }
  return "";
}

//////////////////////////////////////上传
var set_hex_devicecommand = function(mac, up_hex) {
  console.log("上传参数", mac, up_hex);

  if(mac != "" && up_hex != "" && (up_hex.startsWith("66"))) {
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/dyeRecord/setBluetoothCommand?deviceMac=' + mac + '&hex='+up_hex,
      method: 'post',
    }, (res) => {
      if(res && res.data) {
        console.log('回复指令',res.data);
        if(res.data.toLowerCase().indexOf('66000080') == 0) {
          write_value(res.data);
        }
      }
    })
  }

  
  
  // wx.request({
  //   url: app.globalData.api + "/device.ashx",
  //   data: {
  //     ac: "set_hex_devicecommand",
  //     deviceid: deviceid,
  //     hex: up_hex
  //   },
  //   method: 'POST',
  //   header: {
  //     "Content-Type": "application/x-www-form-urlencoded"
  //   },
  //   dataType: "json",
  //   success: function(res) {
  //     if (res.data.code > 0) {} else {
  //       //  setTimeout(function() {
  //       //   wx.showModal({
  //       //     title: '',
  //       //     content: res.data.message,
  //       //   });
  //       // }, 200);
  //     }
  //   },
  //   fail: function(res) {
  //     wx.showToast({
  //       title: res.errMsg,
  //       duration: 1000,
  //       mask: false
  //     });
  //   },
  //   complete: function() {
  //     wx.hideLoading();
  //   }
  // });
}

var interval_bt = function() {
  bt_setInterval = setInterval(write_bt, 1000);
}
var write_no = function() {
  //console.log('清除2222222222222')
  clearInterval(bt_setInterval);
}

var write_bt = function() {
  // if (!that.data.write)
  //   return;
  //55000b02010000001120e9fd2eb1f102b53f0988e2f24336965d18102121071400000000000000000000b855
  //55000B02010000001120E9FD2EB1F102B53F0988E2F24336965D18102121071400000000000000000000B855

  // var buf = util.hexString2ArrayBuffer("A5");
  // if (down_hex && ok_write) {
  //   buf = util.hexString2ArrayBuffer(down_hex.toUpperCase());
  //   down_hex = "";
  //   ok_write = false;
  // }
  // var buf = new ArrayBuffer(1);
  // let dataView = new DataView(buf)
  // dataView.setUint8(0, 0xA5);
  //console.log("写入:" + util.arrayBuffer2HexString(buf) + " bluetooth.bluetooth.down_hex=" + down_hex);
  var str = "A5";
  if (down_hex && ok_write) {
    str = down_hex.toUpperCase();
    down_hex = "";
    //ok_write = false;
  }
  ok_write = false;
  write_value(str);
}

var set_down_hex = function(hex) {
  down_hex = hex;
}
var set_ok_write = function(b) {
  ok_write = b;
}

var bluetooth = {
  openBlue: openBlue,
  write_bt: write_bt,
  init: init,
  lanya3: lanya3,
  lanya4: lanya4,
  lanya7: lanya7,
  connectTO: connectTO,
  write_value: write_value,
  lanya8: lanya8,
  lanya9: lanya9,
  lanya10: lanya10,
  status: status,
  sousuo: sousuo,
  connectedDeviceId: connectedDeviceId,
  services: services,
  characteristics: characteristics,
  writeServicweId: writeServicweId,
  writeCharacteristicsId: writeCharacteristicsId,
  readServicweId: readServicweId,
  readCharacteristicsId: readCharacteristicsId,
  notifyServicweId: notifyServicweId,
  notifyCharacteristicsId: notifyCharacteristicsId,
  inputValue: inputValue,
  characteristics1: characteristics1,

  //mac: mac,
  set_down_hex: set_down_hex,
  check_bt: check_bt,
  bt_temp_data: bt_temp_data,
  get_bt_data: get_bt_data,
  set_hex_devicecommand: set_hex_devicecommand,
  close_bt: close_bt,
  set_ok_write: set_ok_write,
  interval_bt: interval_bt,
  write_no: write_no
}


module.exports = {
  bluetooth: bluetooth
}